<template>
  <el-dialog
    v-model="visible"
    title="编辑用户"
    width="500px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入账号" disabled />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
          <el-option label="未知" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="用户类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择用户类型" style="width: 100%">
          <el-option label="超级管理员" :value="0" />
          <el-option label="管理员" :value="1" />
          <el-option label="普通用户" :value="2" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from '@/plugins/axios'

export default {
  name: 'EditUserDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    userData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const visible = ref(false)
    const loading = ref(false)
    const formRef = ref()
    
    const form = reactive({
      id: '',
      username: '',
      account: '',
      email: '',
      phone: '',
      gender: 0,
      type: 2, // 2代表普通用户
      status: 1
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ]
    }
    
    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal
      if (newVal && props.userData) {
        initForm()
      }
    })
    
    watch(visible, (newVal) => {
      emit('update:modelValue', newVal)
    })
    
    // 初始化表单数据
    const initForm = () => {
      Object.assign(form, {
        id: props.userData.id || '',
        username: props.userData.username || '',
        account: props.userData.account || '',
        email: props.userData.email || '',
        phone: props.userData.phone || '',
        gender: props.userData.gender !== undefined ? props.userData.gender : 0,
        type: props.userData.type !== undefined ? 
              (typeof props.userData.type === 'string' ? 
                (props.userData.type === 'super_admin' ? 0 : 
                 props.userData.type === 'admin' ? 1 : 2) : 
                props.userData.type) : 2,
        status: props.userData.status !== undefined ? props.userData.status : 1
      })
      
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    const handleClose = () => {
      visible.value = false
    }
    
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        loading.value = true
        
        // 调用后端API更新用户
        const response = await axios.post('/user/update', form)
        
        if (response.data.code === 1) {
          ElMessage.success('用户更新成功')
          emit('success')
          handleClose()
        } else {
          ElMessage.error(response.data.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新用户失败:', error)
        if (error.response) {
          ElMessage.error(error.response.data?.msg || '更新失败，请检查网络连接')
        } else {
          ElMessage.error('更新失败，请检查网络连接')
        }
      } finally {
        loading.value = false
      }
    }
    
    return {
      visible,
      loading,
      formRef,
      form,
      rules,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>